/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import path from 'path';

import { InputFile, InputFiles } from '@ohos/hvigor';
import fse from 'fs-extra';

import { CommonConst } from '../../const/common-const.js';
import { LegacyTargetSourceSetModel } from '../../model/source-set/source-set-model.js';
import { ModuleBuildProfile } from '../../options/build/module-build-profile.js';
import { ConfigJson } from '../../options/configure/config-json-options.js';
import { AbstractGenerateMetadata } from '../abstract/abstract-generate-metadata.js';
import { TaskNames } from '../common/task-names.js';
import { ModuleTargetData } from '../data/hap-task-target-data.js';
import { TargetTaskService } from '../service/target-task-service.js';

import LegacyFATask = TaskNames.LegacyFATask;
import ConfigOptObj = ConfigJson.ConfigOptObj;

/**
 * Legacy Generate OutputMetadata Task
 */
export class LegacyGenerateMetadata extends AbstractGenerateMetadata {
  @InputFile() private readonly configJsonPath: string;

  @InputFiles() private get relatedEntryJsonList(): string[] {
    return this.getRelatedEntryJsonList(CommonConst.CONFIG_JSON);
  }

  constructor(targetService: TargetTaskService) {
    super(targetService, LegacyFATask.GENERATE_METADATA);
    const sourceSetModel = this.sourceSetModel as LegacyTargetSourceSetModel;
    this.configJsonPath = sourceSetModel.getLegacyModuleTargetRes().getJsonPath();
  }

  protected getDistroFilterObj(relatedEntryTargetData: ModuleTargetData): ModuleBuildProfile.DistroFilterBuildOpt | undefined {
    const moduleSourceSetModel = relatedEntryTargetData.getModuleSourceSetModel() as LegacyTargetSourceSetModel;
    const configJsonPath = path.resolve(moduleSourceSetModel.getLegacyModuleTargetRes().getJsonPath());
    const configJsonObj: ConfigOptObj = fse.readJsonSync(configJsonPath);
    const distroFilter = configJsonObj.module.distroFilter;
    const targetDistroFilter = relatedEntryTargetData.getTargetOpt().config?.distroFilter;
    return targetDistroFilter ?? distroFilter;
  }
}
